<?php
/**
 * Created by PhpStorm.
 * User: liuxiaojie
 * Date: 2019-03-05
 * Time: 16:46
 */

namespace app\api\controller;

use app\common\BaseLoginCustomer;
use app\model\MoneyLog;
use app\model\MyCoupon;
use app\model\Order;
use app\model\Prize;
use app\tools\Helper;
use app\tools\Log;
use app\tools\MIniprogram;
use app\tools\RedisCache;
use app\tools\RedPacket;
use think\Db;

class Customer extends BaseLoginCustomer
{

    // 绑定推广码

    function setCode(){

        $code = $this->getParam('promo_code', '');
        $u_id = $this->getParam('u_id', 0);
        $address = $this->getParam('address', '');
        $lat = $this->getParam('lat', 0);
        $lng = $this->getParam('lng', 0);

        if(!$code || !$address){
            return fail("DATA_ERROR");
        }

        $p_code = db('customer')->where(["id"=> $u_id])->value('code');
        if($p_code){
            return fail("HAS_BIND");
        }

        $status = \db('promo_code')->where(['code'=> $code])->value('status');
        if($status == 0){
            return fail("CODE_HAS_BIND");
        }

        Db::startTrans();
        try{
            $code_id = \db('promo_code')->where(['code'=> $code])->value('id');
            if(!$code_id){
                Db::rollback();
                return fail("PROMO_CODE_NOT_FOUND");
            }

            db('customer')->where(['id'=> $u_id])->update(['code'=> $code, 'address'=> $address, 'lat'=> $lat, 'lng'=> $lng]);
            db('promo_code')->where(['id'=> $code_id])->update(['status'=> 0]);

            Db::commit();
        }catch (\Exception $exception){

            Db::rollback();
            return fail();

        }

        return success([]);
    }

    // 用户信息
    function info(){

        $u_id = $this->getParam('u_id', 0);

        $data = db('customer')->where(['id'=> $u_id])->field('money, money_xn, tiger_tee, code, diam')->find();

        $list = \db('repair_person')->where(['customer_id'=> $u_id])->field('status')->find();
        $data['status'] = $list['status'];

        $waitUse = MyCoupon::where(['status'=> 1, 'customer_id'=> $u_id, 'o_id'=> ['>', 0]])->count('distinct o_id');
        $waitEval = Order::where(['status'=> 30, 'customer_id'=> $u_id])->count();
        $red = $count = \app\model\Customer::where(['id'=> $u_id])->value('redpacket_num');

        $data['wait_use'] = $waitUse;
        $data['wait_eval'] = $waitEval;
        $data['red_packet'] = $red;
        $data['total_money'] = $data['money'] + $data['money_xn'];

        return success($data);
    }

    //
    function income(){
        $u_id = $this->getParam('u_id', 0);
        $page = $this->getParam('page', 1);
        $page_size = $this->getParam('page_size', 10);

        $info = db('customer')->where(['id'=> $u_id])->field('code, money, address, lat, lng')->find();

        $where = [
          'value'=> ['>', 0],
          'type'=> 1,
          'u_id'=> $u_id,
          'reason_type'=> ['in', [1, 2, 12, 13, 14]]
        ];
        $total_money = db('money_log')->where($where)->sum('value');

        $info['total'] = $total_money;

        $where = [
            'value'=> ['>', 0],
            'u_id'=> $u_id,
            'create_time'=> ['between', [date('Y-m-d'), date("Y-m-d", strtotime("1 day"))]],
            'reason_type'=> ['in', [1, 2, 12, 13, 14]]
        ];

        $day = db('money_log')->where($where)->field('sum(value) as total, type')->group('type')->select();

        $day = array_column($day, 'total', 'type');

        $info['day_money'] = floatval($day[1]);
        $info['day_tiger_tee'] = intval($day[2]);

        $where = [
            'm.value'=> ['>', 0],
            'm.u_id'=> $u_id,
            'm.reason_type'=> ['in', [1, 2, 12, 13, 14]]
        ];

        $list = db('money_log m')
            ->join('customer c', 'm.child_id = c.id', 'left')
            ->where($where)
            ->field('c.avatar_url, c.nickname, m.create_time, m.type, m.value, m.reason, m.reason_type')
            ->page($page, $page_size)
            ->order('m.id desc')
            ->select();

        $info['list'] = $list;
        return success($info);

    }

    // 提现
    function withdrawals(){

        $total_money = $this->getParam('total_money', 0);
        $num = 1;
        $customer_id = $this->getParam('u_id', 0);

        $key = "withdrawals_".$customer_id;
        $redis = RedisCache::getInstance();

        if($redis->get($key)){
            return fail("OPERATION_OFTEN");
        }

        $redis->setex($key, 2, 1);

        if($total_money > 200 || $total_money < 1){
            return fail("MONEY_NOT_RIGHT");
        }

        $total = $total_money * $num;

        $info = db('customer')->where(['id'=> $customer_id])->field('id, money, unionid')->find();

        if($total > $info['money']){
            return fail("MONEY_NOT_ENOUGH");
        }

        $post = [
            'total_money'=> $total_money,
            'num'=> $num,
            'customer_id'=> $customer_id,
            'order_no'=> Helper::createOrderSn()
        ];

        Db::startTrans();
        try{
            db('withdrawals_order')->insert($post);
            db('customer')->where(['id'=> $info['id']])->setDec("money", $total);

            MoneyLog::addLog([
                "child_id"=> 0,
                "u_id"=> $customer_id,
                "type"=> 1,
                "value"=> -$total,
                "reason_type"=> 3
            ]);

            $openid = \db('customer')->where(['unionid'=> $info['unionid'], 'type'=>2])->value('openid');

            $red_pack = new RedPacket();
            $status = $red_pack->ordinary([
                "mch_billno"=> $post['order_no'],
                "re_openid"=> $openid,
                "total_amount"=> $total_money*100,
                "total_num"=> $num,
                "act_name"=> "红包提现",
                "remark"=> "",
                "scene_id"=> "PRODUCT_5",

            ]);

            if($status !== true){

                Db::rollback();
                file_put_contents('1.txt', $status);
                return fail();
            }

            Db::commit();

        }catch (\Exception $exception){
            Db::rollback();
//            echo $exception->getMessage();
            file_put_contents('1.txt', $exception->getMessage());
            return fail();
        }

        $last = db('customer')->where(['id'=> $customer_id])->value('money');

        return success(['money'=> $last]);


    }

    function updateData()
    {
        $data = [
            'id'=> $this->getParam('u_id', 0),
            'nickname'=> $this->getParam('nickname', ''),
            'gender'=> $this->getParam('gender', 0),
            'city'=> $this->getParam('city', ''),
            'province'=> $this->getParam('province', ''),
            'country'=> $this->getParam('country', ''),
            'avatar_url'=> $this->getParam('avatar_url', ''),
        ];

        db('customer')->update($data);

        return success([]);

    }


}